package com.tjh.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.tjh.common.constant.AuthServerConstant;
import com.tjh.common.exception.BizCodeEnume;
import com.tjh.common.utils.R;
import com.tjh.common.vo.MemberRespVo;
import com.tjh.gulimall.auth.feign.MemberFeignService;
import com.tjh.gulimall.auth.vo.UserLoginVo;
import com.tjh.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Create by koala on 2021-05-06
 */

@Controller
@Slf4j
public class LoginController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    //day96: 获取手机短信验证码
    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        // TODO: 2020/9/28 //1.接口防刷
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 6000) {
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //2.验证码再次验证
        String code = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        String subString = code + "_" + System.currentTimeMillis();
        //redis缓存验证码，防止同一个phone在60s内再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, subString, 10, TimeUnit.MINUTES);
        //thirdPartFeignService.sendCode(phone,code);
        log.info(">>>>>>>>>code:" + code);

        return R.ok();
    }

    /**
     * day97：用户注册
     * 测试：
     *      浏览器访问注册页，进行注册操作
     *      http://auth.gulimall.com/reg.html
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            //校验出错，转发到注册页
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //1.校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (StringUtils.isEmpty(s)) {//此处本应该取反（if (!StringUtils.isEmpty(s))）：因为该系统未接入阿里短信无法校验验证码，故此处不取反
            // if (code.equals(s.split("_")[0])) {
            if (true) {
                //删除验证码，令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码验证通过 /真正注册  调用远程服务进行注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    //成功

                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String,String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    //校验出错转发到注册页
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            }else {
                Map<String,String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                //校验出错转发到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //return "redirect:/login.html";
    }

    /**
     * day98：登录
     */
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登录
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {//登录成功，

            /**
             * day100：自定义SpringSession完成子域session共享
             * 测试：
             *      1、浏览器访问 http://gulimall.com/
             *      2、点击登录链接跳转登录页
             *      3、选择 微博登录/账号 进行登录
             *      4、回到首页，并看到首页显示用户名该模块即是成功的
             *      5、亦可查看redis，若redis中的 spring session sessions 下存在数据表明登录的用户数据成功存入了redis
             */
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);

            return "redirect:http://gulimall.com";
        }else {
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    /**
     * day101：判断用户是否已登录状态，已登录状态则返回首页，否则去登录页
     * 测试：
     *      1、浏览器访问：http://auth.gulimall.com/login.html
     *      2、若用户已登录，则跳转到首页
     *      3、若用户未登录，则跳转到登录页
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            //没登录
            return "login";
        }

        return "redirect:http://gulimall.com";
    }

}
